package com.ai.sml.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;

public class FreemarkerFilter implements Filter {
	private FilterConfig filterConfig;
	private static final Logger logger = LoggerFactory.getServiceLog(FreemarkerFilter.class);

	public void destroy() {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		response.setHeader("pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		String filePath = StringUtils.substringAfter(request.getRequestURI().toString(), request.getContextPath());
		// String htmlPath = filterConfig.getServletContext().getRealPath("/");
		long start = System.currentTimeMillis();
		logger.info("Freemarker Engine process start", "FilePath=" + filePath);
		FreemarkerEngine freemarkerEngine = FreemarkerEngine.getInstance(filterConfig.getServletContext());
		try {
			Map<String, String> param = getParameter(request);
			setToken(request, param);
			/*try {
				param.put("nginx_uri", PropertiesUtil.getString("SYSTEM_NGINX_URI"));
				Subject subject = SecurityUtils.getSubject();
				Session session = subject.getSession();
				param.put("userId", (String) session.getAttribute("userId"));
				param.put("linkNm", (String) session.getAttribute("linkNm"));
				param.put("linkPhone", (String) session.getAttribute("linkPhone"));
			} catch (Exception e) {
				logger.error("Freemarker Engine end", e.getMessage(), e);
			}*/
			freemarkerEngine.process(param, filePath, response);
			long end = System.currentTimeMillis();
			logger.info("Freemarker Engine end", "cost " + (end - start) + " ms");
			return;
		} catch (Exception e) {
			logger.error("Freemarker Engine end", e.getMessage(), e);
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	/** TOKEN */
	protected void setToken(HttpServletRequest request, Map<String, String> param) {
		HttpSession session = request.getSession();
		Long token = System.currentTimeMillis();
		param.put("token", token + "");
		Integer size = (Integer) session.getAttribute("_my_token_size");
		if (size == null) {
			size = 0;
		}
		size++;
		param.put("token_size", size.toString());
		session.setAttribute("_my_token_size", size);
		session.setAttribute("_my_token_" + size, token);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	@SuppressWarnings("unchecked")
	private Map<String, String> getParameter(HttpServletRequest request) {
		Enumeration<String> enumeration = request.getParameterNames();
		Map<String, String> param = new HashMap<String, String>();
		while (enumeration.hasMoreElements()) {
			String key = enumeration.nextElement();
			String value = request.getParameter(key);
			param.put(key, value);
		}
		return param;
	}
}
